<?php

namespace app\common\model;

use think\Model;


class Cart extends Model
{





    // 表名
    protected $name = 'cart';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [];


    public function goods()
    {
        return $this->belongsTo('Goods', 'goods_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
    public static function addCart($param)
    {
        $model = new self;
        $cart = $model->where('goods_id', $param['goods_id'])->where('user_id', $param['uid'])->find();
        if ($cart) {
            if ($cart['num'] <= 0) {
                $model->delete();
            } else {
                $cart->allowField(true)->save(['num' => $param['num']]);
            }
            return  $cart->id;
        } else {
            $data = [
                'user_id' => $param['uid'],
                'goods_id' => $param['goods_id'],
                'num' => $param['num'],
            ];
            if ($param['num'] > 0) {
                $model->allowField(true)->save($data);
                return  $model->id;
            }
        }
        return false;
    }

    //删除购物车
    public static function delCart($uid, $goods_ids)
    {
        $model = new self;
        return $model->where('user_id', $uid)->whereIn('id', $goods_ids)->delete();
    }
    //购物车列表
    public static function list($uid)
    {
        $model = new self;
        $list = $model->with(['goods'])->whereIn('user_id', $uid)->select();
        return $list;
    }

    //获取购物车下单商品信息
    public static function getGoods($ids, $uid)
    {
        $cart_goods = Cart::with('goods')->whereIn('cart.id', $ids)->where('user_id', $uid)->select();

        foreach ($cart_goods as &$v) {
            if ($v->goods->stock < $v->num) {
                return exception('商品【' . $v->goods->title . '】库存不足，不能下单');
            }
            if ($v->goods->status == '0') {
                return exception('商品【' . $v->goods->title . '】已下架，不能下单');
            }
            if ($v->goods->deletetime != null) {
                return exception('商品【' . $v->goods->title . '】已删除，不能下单');
            }
            $v->money = $v->num * $v->goods->price;
            $v->original = $v->num * $v->goods->original_price;
        }
        return $cart_goods;
    }
}
